let params = new URLSearchParams(location.search)
let title = document.querySelector('.title')
let yes = document.querySelector('[value*="确认"]')
let no = document.querySelector('[value*="取消"]')
let [stuName , stuAge , stuClass] = document.querySelectorAll('input[name]')

function Useaxios(method , url) {
    axios({
        method,
        url,
        data: {
            stuName : stuName.value,
            stuAge : stuAge.value, 
            stuClass : stuClass.value
        }
    })
    .then(() => {
        location.href = './index.html'
    })
    .catch(err => {
        console.log(err)
    })
}

if(params.get('id')){
    title.innerHTML = '修改页面'
    yes.value = '确认修改'
    no.value = '取消修改'
    axios({
        method:'get',
        url: `http://student.ayulin.cn:8000/${params.get('id')}`,
    })
    .then(res => {
        let oneStudent = res.data
        stuName.value = oneStudent.stuName
        stuAge.value = oneStudent.stuAge
        stuClass.value = oneStudent.stuClass
    })
    .catch(err => {
        console.log(err)
    })
}else{
    title.innerHTML = '新增页面'
    yes.value = '确认添加'
    no.value = '取消添加'
}


no.addEventListener('click',() => {
    location.href = './index.html'
})

yes.addEventListener('click',() => {
    let isGo = true 
    
    if(!(/^[\u4e00-\u9fa5a-zA-Z]{2,6}$/).test(stuName.value)){
        alert('姓名的字符只能是大小写字母或者汉字，长度需在 2 ~ 6 之间（包含 2 到 6）')
        isGo = false
    }
    if(!(/^[0-9]{1,2}$/).test(stuAge.value)){
        alert('年龄的字符只能是数字，并且长度只能是 1 ~ 2 （包含 1 到 2）')
        isGo = false
    }
    if(!(/^[\u4e00-\u9fa5a-zA-Z0-9]{2,10}$/).test(stuClass.value)){
        alert('班级的字符只能是大小写字母、汉字或者数字，并且长度只能是 2 ~ 10 （包含 2 到 10）')
        isGo = false
    }
    if(stuAge.value <= 0 || stuAge.value >100){
        alert('年龄输入有误，请重新输入')
        isGo = false
    }
    if(isGo){
        if(params.get('id')){
            Useaxios('put',`http://student.ayulin.cn:8000/${params.get('id')}`)
        }else{
            Useaxios('post',`http://student.ayulin.cn:8000`)
        }
    }
})

